﻿using Newtonsoft.Json;
using System.Linq.Expressions;

namespace System;

public static class ExpressionBasicExtension
{
    public static Expression<Func<TClass, TProperty>> BuildProperty<TClass, TProperty>(string fieldName)
    {
        var param = Expression.Parameter(typeof(TClass));
        var field = Expression.PropertyOrField(param, fieldName);
        return Expression.Lambda<Func<TClass, TProperty>>(field, param);
    }

    public static List<object> GetExpressionParam(this Expression<Func<Task>> expression)
    {
        List<object> paras = null;
        if (expression.Body is MethodCallExpression methodCall)
        {
            ParameterInfo[] paraTypes = methodCall.Method.GetParameters();
            Collections.ObjectModel.ReadOnlyCollection<Expression> arguments = methodCall.Arguments;
            if (arguments?.Count > 0)
            {
                paras = new List<object>(arguments.Count);
                for (int i = 0; i < paraTypes.Length; i++)
                {
                    ParameterInfo paraInfo = paraTypes[i];
                    if (arguments[i] is MemberExpression member)
                    {
                        dynamic feildExpression = member.Expression;
                        if (feildExpression != null)
                        {
                            string memberName = paraInfo.Name;
                            var value = feildExpression.Value;
                            object valObj = value;
                            var valType = valObj.GetType();
                            PropertyInfo? prop = valType.GetProperty(memberName);
                            var finalValue = prop.GetValue(valObj);

                            paras.Add(feildExpression.Value);
                            string json = JsonConvert.SerializeObject(feildExpression.Value);
                        }
                    }
                }
            }
        }
        return paras;
    }

}